<template>
  <div class="box">
      <header class="header">
        <van-nav-bar title="购物车" left-arrow @click-left="$router.back()"></van-nav-bar>
      </header>
      <section class="content">
        <van-notice-bar color="#1989fa" v-if="$store.state.cart.cartlist.length > 0" background="#ecf9ff" left-icon="info-o" mode="closeable">
          向左滑动删除商品
        </van-notice-bar>
        <van-empty v-if="$store.state.cart.cartlist.length === 0" image="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png" description="购物车空空如也">
          <van-button round type="danger" class="bottom-button" @click="$router.push('/classify')">
            去购物
          </van-button>
        </van-empty>
        <van-swipe-cell v-else v-for="(item, index) of $store.state.cart.cartlist" :key="item.proid">
          <van-card :price="item.price" :title="item.proname">
            <template #thumb>
              <van-checkbox v-model="item.flag" @click="changeItemFlag(item)"></van-checkbox>
              <van-image :src="item.proimg" />
            </template>
            <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" disable-input @change="changeNum(item)"/>
            </template>
          </van-card>
          <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="deleteCart(item.cartid, index)"/>
          </template>
        </van-swipe-cell>
        <van-submit-bar v-if="$store.state.cart.cartlist.length > 0"
          :disabled="totalNum === 0" :price="totalPrice * 100" :button-text="'去结算(' + totalNum + ')'" @submit="onSubmit">
          <van-checkbox v-model="checked" @click="selectAll">全选</van-checkbox>
        </van-submit-bar>
      </section>
    </div>
</template>

<script>
import Vue from 'vue'
import { Card, Button, Stepper, SwipeCell, NoticeBar, Empty, SubmitBar, Checkbox, Toast, Dialog, Image as VanImage, NavBar } from 'vant'
import { getCartData, deleteCartData, updateCartNum, updateAllFlag, updateFlag } from '@/api'
import { orderAdd } from '@/api/order'
import { mapState } from 'vuex'

Vue.use(Card)
Vue.use(Button)
Vue.use(Stepper)
Vue.use(SwipeCell)
Vue.use(NoticeBar)
Vue.use(Empty)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(Dialog)
Vue.use(VanImage)
Vue.use(NavBar)

export default {
  data () {
    return {
      checked: false
    }
  },
  methods: {
    onSubmit () {
      // console.log('去结算')
      const arr = this.$store.state.cart.cartlist.filter(item => {
        return item.flag
      })
      orderAdd({
        list: arr
      }).then(res => {
        // console.log(res)
        this.$router.push('/order/' + res.data.data)
      })
      // console.log(arr)
    },
    deleteCart (cartid, index) {
      Dialog.confirm({
        message: '是否确认删除？'
      })
        .then(() => {
          // on confirm
          deleteCartData({ cartid }).then(res => {
            if (res.data.code === '200') {
              Toast('删除成功')
              // 改变列表数据
              const arr = this.$store.state.cart.cartlist
              arr.splice(index, 1)
              this.$store.commit('cart/change_cart_list', arr)
              const allFlag = this.$store.state.cart.cartlist.every(item => item.flag)
              this.checked = allFlag
            }
          })
        })
        .catch(() => {
          // on cancel
        })
    },
    changeNum (item) {
      // console.log(item.num)
      updateCartNum({
        cartid: item.cartid,
        num: item.num
      }).then(res => {
        if (res.data.code === '200') {
          Toast('更新购物车成功')
        }
      })
    },
    changeItemFlag (item) {
      // console.log(item.flag)
      updateFlag({
        cartid: item.cartid,
        checked: item.flag
      }).then(() => {
        if (item.flag) {
          // 当前的被选中，判断其余的有没有都被选中
          const test = this.$store.state.cart.cartlist.every(item => {
            return item.flag
          })
          if (test) {
            this.checked = true
          } else {
            this.checked = false
          }
        } else {
          this.checked = false
        }
      })
    },
    selectAll () {
      // console.log(this.checked)
      updateAllFlag({
        userid: localStorage.getItem('userid'),
        checked: this.checked
      }).then(res => {
        if (this.checked) {
          const arr = this.$store.state.cart.cartlist
          arr.forEach(item => {
            item.flag = true
          })
          this.$store.commit('cart/change_cart_list', arr)
        } else {
          const arr = this.$store.state.cart.cartlist
          arr.forEach(item => {
            item.flag = false
          })
          this.$store.commit('cart/change_cart_list', arr)
        }
      })
    }
  },
  computed: {
    ...mapState({
      // cartlist: (state) => { return state.cart.cartlist }
      cartlist: ({ cart: { cartlist } }) => cartlist
    }),
    totalNum () {
      return this.$store.state.cart.cartlist.reduce((sum, item) => {
        // reduce() 方法接收一个函数作为累加器，数组中的每个值（从左到右）开始缩减，最终计算为一个值。reduce() 可以作为一个高阶函数，用于函数的 compose。注意: reduce() 对于空数组是不会执行回调函数的。
        return item.flag ? sum + item.num : sum + 0
      }, 0)
    },
    totalPrice () {
      return this.$store.state.cart.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.num * item.price : sum + 0
      }, 0)
    }
  },
  mounted () {
    getCartData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      this.$store.commit('cart/change_cart_list', res.data.data)
      // 实时获取 列表状态 推算全选的默认值
      this.checked = this.$store.state.cart.cartlist.every(item => {
        return item.flag
      })
    })
  }
}
</script>

<style lang="scss" scoped>
  .delete-button {
    height: 100%;
  }
  .van-submit-bar {
    bottom: 0.6rem;
  }
  .bottom-button {
    width: 160px;
    height: 40px;
  }
  .van-card {
    background: #fff;
  }
  .van-card__thumb {
    width: 128px;
    display: flex;
    .van-checkbox {
      width: 40px;
    }
    .van-image {
      width: 88px;
    }
  }
</style>
